package com.kungfuhacking.wristbandpro.location.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Marker;
import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.base.view.BaseActivity;
import com.kungfuhacking.wristbandpro.location.bean.HistoryLocationBean;
import com.kungfuhacking.wristbandpro.location.presenter.IHistoryPresenter;
import com.kungfuhacking.wristbandpro.location.presenter.SimpleAdapter;
import com.kungfuhacking.wristbandpro.location.view.IHistoryView;
import com.kungfuhacking.wristbandpro.utils.AbDateUtil;
import com.kungfuhacking.wristbandpro.utils.DensityUtil;
import com.kungfuhacking.wristbandpro.utils.LogUtil;
import com.kungfuhacking.wristbandpro.widget.BatteryView;

import java.util.Date;

import static com.kungfuhacking.wristbandpro.R.id.tv_title;


/**
 * 历史轨迹页面
 * Created by Aaron on 17/5/9.
 */

public class HistoryActivity extends BaseActivity implements IHistoryView, View.OnClickListener {

    private android.widget.ImageView ivleft;
    private android.widget.TextView tvtitle;
    private android.widget.TextView tvright;
    //    private android.widget.TextView tvtimeinfo;
    private MapView mapView;
    private IHistoryPresenter iHistoryPresenter = new IHistoryPresenter(this);
    private AMapLocationClient mLocationClient;
    private long firstTimeOfDay = AbDateUtil.getFirstTimeOfDay();
    private String TAG = getClass().getSimpleName();
    private BitmapDescriptor des = null;
    private PopupWindow areaPup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_history);
        initWidget();
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        initMap();
        long startTime = new Date().getTime() - 2 * 60 * 60 * 1000;

        iHistoryPresenter.getHistoryRecord(startTime, new Date().getTime());
//        iHistoryPresenter.getHistoryRecord(firstTimeOfDay, new Date().getTime());

//        Date date = new Date();
//        date.setTime(startTime);
//        Calendar instance = Calendar.getInstance();
//        instance.setTime(date);
//        int hour = instance.get(GregorianCalendar.HOUR);
//        int minute = instance.get(GregorianCalendar.MINUTE);
//        Log.d(TAG, "定位开始时间:" + hour + ",:" + minute);

    }

    private void initWidget() {

        this.mapView = (MapView) findViewById(R.id.gdmap);
//        this.tvtimeinfo = (TextView) findViewById(R.id.tv_time_info);
        this.tvright = (TextView) findViewById(R.id.tv_right);
        this.tvtitle = (TextView) findViewById(tv_title);
        this.ivleft = (ImageView) findViewById(R.id.iv_left);

        tvright.setText(getResources().getString(R.string.today));
        tvtitle.setText(getResources().getString(R.string.time_select));

        ivleft.setOnClickListener(this);
        tvright.setOnClickListener(this);
        tvtitle.setOnClickListener(this);
    }

    private void initMap() {
        mLocationClient = new AMapLocationClient(this);
        iHistoryPresenter.initMap(mapView.getMap(), mLocationClient);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (mapView != null)
            mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null)
            mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();

        iHistoryPresenter.clearRequest();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;
            case R.id.tv_right://选择日期
//                nextActivity(ChooseDateActivity.class);
                nextActivityWithCode(ChooseDateActivity.class, 0x33333);
                break;

            case R.id.tv_title://选择时间段
                selectTimeQuantum(v);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x33333 && resultCode == 0x33334) {
            if (data == null)
                return;

            //选择的日期
            firstTimeOfDay = data.getLongExtra("date", 0);
            tvright.setText(data.getStringExtra("showDate"));
            selectTimeQuantum(tvtitle);
        }

    }

    @Override
    public BitmapDescriptor getBitmap() {
        if (des == null) {
            Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                    R.mipmap.ic_thumb);
            des = BitmapDescriptorFactory.fromBitmap(bMap);
        }
        return des;
    }

    @Override
    public View getMarkerView(Marker marker) {

        LayoutInflater inflater = getLayoutInflater();

        View windowView = inflater.inflate(R.layout.layout_showbaby_location, null);
        windowView.setPadding(5, 5, 5, 5);

        TextView tv_barry = (TextView) windowView.findViewById(R.id.tv_barry);
        TextView tv_time = (TextView) windowView.findViewById(R.id.tv_time);
        BatteryView iv_barry = (BatteryView) windowView.findViewById(R.id.iv_barry);
        TextView adrress = (TextView) windowView.findViewById(R.id.adrress);
        HistoryLocationBean info = (HistoryLocationBean) marker.getObject();

        if (info == null)
            return null;

        LogUtil.d(TAG, "getInfoWindow markInfo :" + info.getUpdateTime()
                + "," + info.get_id()
                + "," + info.getBattery()
                + "," + info.getSn()
                + "," + info.getLatitude());

        tv_time.setText(AbDateUtil.getStringByFormat(info.getUpdateTime(), "yyyy-MM-dd HH:mm:ss") + "  (" + info.getProvider() +"定位)");
        adrress.setText(info.getAddressDescription());
        tv_barry.setText(info.getBattery() + "%");

        if (!TextUtils.isEmpty(info.getBattery())) {

            tv_barry.setText(info.getBattery() + "%");
            int currentBattery = Integer.parseInt(info.getBattery());

            iv_barry.setLength(28, 12, 5, 10, 1);
            if (currentBattery <= 20) //电量小于20变红
                iv_barry.setColor(Color.BLACK, Color.RED);
            else  //大于20是绿的
                iv_barry.setColor(Color.BLACK, Color.GREEN);

            iv_barry.setPower(currentBattery <= 10 ? 10 : currentBattery);

        }

        return windowView;
    }

    /**
     * 选择时间段
     */
    @Deprecated
    private void selectTimeQuantum(View v) {

        View popuView = View.inflate(this, R.layout.popup_choose_time_quantum, null);

        areaPup = new PopupWindow(popuView,
                DensityUtil.dip2px(this, 150), DensityUtil.dip2px(this, 300));
        areaPup.setOutsideTouchable(true);

        areaPup.setFocusable(true);
        areaPup.setBackgroundDrawable(new BitmapDrawable());
        //x y
        areaPup.showAsDropDown(v, 0, 0);

        ListView lv_time = (ListView) popuView.findViewById(R.id.lv_time);
        SimpleAdapter adapter = new SimpleAdapter(this, getResources().getStringArray(R.array.tims_quantum));
        lv_time.setAdapter(adapter);

        lv_time.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (areaPup != null && areaPup.isShowing())
                    areaPup.dismiss();

                //获取到选择的开始时间和结束时间
                long firstTime = firstTimeOfDay + (2L * 60 * 60 * 1000) * i;
                long lastTime = firstTime + (2L * 60 * 60 * 1000);
                tvtitle.setText(getResources().getStringArray(R.array.tims_quantum)[i]);
//                tvtimeinfo.setText(tvtitle.getText().toString() + "的部分活动轨迹");
                iHistoryPresenter.getHistoryRecord(firstTime, lastTime);

            }
        });

    }
}
